package com.wooming.myserver.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wooming.myserver.dto.JwtDTO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 接口调用监控
 *
 * @author Wooming 2025/05/24
 */
public class ApiObserver {

    public static Result<?> observe(String apiType){
        // 从SecurityContextHolder中获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtDTO jwtDTO;
        try {
            // 将认证信息转为JwtDTO
            jwtDTO = new ObjectMapper().readValue(authentication.getName(), JwtDTO.class);
            // 打印访问信息
            System.out.println("用户:" + jwtDTO.getUsername() + "访问"+ apiType + "接口");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error(500, "服务器错误");
        }
        return Result.success(jwtDTO);
    }
}
